<script setup>
import {onBeforeUnmount, onMounted, onUnmounted, ref} from "vue";
import {getFansData, getMyPostData, getPersonalData, getPostData} from "@/api/publish.js";
import dayjs from "dayjs";
import * as echarts from "echarts";

const select = ref('week')


const data = ref({
  monthPersonalData: {},
  weekPersonalData: {}
});
const getData = async () =>{
  const res = await getPersonalData()
  data.value = res.data.data
  console.log(data.value.monthPersonalData)
}
getData()
const calculateTrend = (current, compare) => {
  // 处理非数字或负数对比值
  if (typeof current !== 'number' || typeof compare !== 'number' || compare <= 0 || current <= 0) {
    return ;
  }

  // 正常计算变化率
  const absolute = current - compare;
  if(absolute===0) return ;
  const percent = (absolute / compare) * 100;

  // 格式化百分比（带正负号，保留一位小数）
  const formattedPercent = percent.toFixed(1);
  const relative = `${percent >= 0 ? '+' : ''}${formattedPercent}%`;

  return relative;
};


const posts = ref([
])

const getPosts = async () =>{
  const res = await getMyPostData()
  posts.value = res.data.data
}
getPosts()


// 时间格式化
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleDateString()
}

const postData = ref()
const type = ref('浏览')
const days = ref(7)
const chart = ref(null)
const chartInstance = ref(null)

// 数据存储
const xAxisDates = ref([])
const chartValues = ref([])

const colorConfig = {
  '浏览': { main: '#1890ff', gradient: ['rgba(24, 144, 255, 0.4)', 'rgba(24, 144, 255, 0.01)'] },
  '点赞': { main: '#ff4d4f', gradient: ['rgba(255, 77, 79, 0.4)', 'rgba(255, 77, 79, 0.01)'] },
  '收藏': { main: '#73d13d', gradient: ['rgba(115, 209, 61, 0.4)', 'rgba(115, 209, 61, 0.01)'] },
  '评论': { main: '#9254de', gradient: ['rgba(146, 84, 222, 0.4)', 'rgba(146, 84, 222, 0.01)'] },
  '涨粉': { main: '#36cfc9', gradient: ['rgba(54, 207, 201, 0.4)', 'rgba(54, 207, 201, 0.01)'] }
};
// 悬浮框数据
const hoverData = ref({
  visible: false,
  x: 0,
  y: 0,
  date: '',
  value: 0
})

// 获取初始数据
const getUserData = async () => {
  const res = await getPostData()
  postData.value = res.data.data
  updateChartData('week', '浏览')
  initChart()
}
getUserData()

// 统一更新数据
const updateChartData = (sign, typeParam) => {
  const dataSource = sign === 'week'
    ? postData.value.weekPostDataShift
    : postData.value.monthPostDataShift

  days.value = sign === 'week' ? 7 : 30
  xAxisDates.value = generateDates()

  switch(typeParam) {
    case '浏览': chartValues.value = dataSource.views; break;
    case '点赞': chartValues.value = dataSource.likes; break;
    case '收藏': chartValues.value = dataSource.collects; break;
    case '评论': chartValues.value = dataSource.comments; break;
    case '涨粉': chartValues.value = dataSource.fans; break;
  }
}

// 切换数据
const change = (typeParam, sign) => {
  type.value = typeParam
  updateChartData(sign, typeParam)
  chartInstance.value.setOption(getChartOption())
  chartInstance.value.setOption(getChartOption())
}

// 生成日期序列
const generateDates = () => {
  return Array.from({ length: days.value }, (_, i) =>
    dayjs().subtract(days.value - 1 - i, 'day').format('YYYY-MM-DD')
  )
}

const getChartOption = () => {
  // 获取当前类型对应的颜色配置
  const currentColor = colorConfig[type.value] || colorConfig['浏览'];

  return {
    xAxis: {
      type: 'category',
      data: xAxisDates.value,
      axisLabel: {
        formatter: value => dayjs(value).format('MM-DD')
      }
    },
    yAxis: {
      type: 'value',
      name: `${type.value}数`
    },
    series: [{
      data: chartValues.value,
      type: 'line',
      smooth: true,
      areaStyle: {
        // 使用动态渐变颜色
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: currentColor.gradient[0] },
          { offset: 1, color: currentColor.gradient[1] }
        ])
      },
      itemStyle: {
        // 使用动态主色
        color: currentColor.main
      },
      lineStyle: {
        width: 3,
        // 折线颜色同步变化
        color: currentColor.main
      }
    }]
  }
}
// 初始化图表
const initChart = () => {
  if (chartInstance.value) chartInstance.value.dispose()

  chartInstance.value = echarts.init(chart.value)
  chartInstance.value.setOption(getChartOption())

  // 绑定鼠标事件
  chartInstance.value.on('mouseover', 'series', (event) => {
    const index = event.dataIndex
    console.log(event.event)
    hoverData.value = {
      visible: true,
      x: event.event.offsetX + 290,
      y: event.event.offsetY + 215,
      date: dayjs(xAxisDates.value[index]).format('M月D日'),
      value: chartValues.value[index]
    }
  })

  chartInstance.value.on('mouseout', () => {
    hoverData.value.visible = false
  })
}

// 窗口resize监听
const handleResize = () => chartInstance.value?.resize()
onMounted(() => window.addEventListener('resize', handleResize))
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.value?.dispose()
})

//粉丝数据
const chartEl = ref(null);
let chartInstanceByFans = null;
const activeType = ref('week'); // week | month

// 响应式数据
const chartData = ref({
  week: [],
  month: []
});

const rawData = ref({})
// 获取数据
const fetchData = async () => {
  try {
    const res = await getFansData();
    rawData.value = res.data.data;
    // 处理数据格式
    chartData.value = {
      week: processTimeData(rawData.value.weekFans, 7),
      month: processTimeData(rawData.value.monthFans, 30)
    };

    initChartByFans();
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 处理时间序列数据
const processTimeData = (dataArray, days) => {
  const dates = [];
  const now = dayjs();

  // 生成日期序列
  for (let i = days - 1; i >= 0; i--) {
    dates.push(now.subtract(i, 'day').format('MM-DD'));
  }

  return dates.map((date, index) => ({
    date,
    value: dataArray[index] || 0
  }));
};

// 初始化图表
const initChartByFans = () => {
  if (!chartEl.value) return;

  chartInstanceByFans = echarts.init(chartEl.value);
  updateChart();
};

// 更新图表配置
const updateChart = () => {
  const currentData = chartData.value[activeType.value];

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        const data = params[0];
        return `
          ${data.axisValue}<br/>
          粉丝数: ${data.value}
        `;
      }
    },
    xAxis: {
      type: 'category',
      data: currentData.map(item => item.date),
      axisLabel: {
        rotate: 45,
        interval: activeType.value === 'month' ? 1 : 0,
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [{
      data: currentData.map(item => item.value),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.2
      },
      itemStyle: {
        color: '#1890ff'
      },
      lineStyle: {
        width: 2
      }
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  };

  chartInstanceByFans.setOption(option);
};

// 切换时间范围
const handleChangeType = (type) => {
  activeType.value = type;
  updateChart();
};

// 自适应调整
const handleResizeByFans = () => {
  chartInstanceByFans?.resize();
};

onMounted(() => {
  fetchData();
  window.addEventListener('resize', handleResizeByFans);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResizeByFans);
  chartInstanceByFans?.dispose();
});
</script>

<template>
<div class="main">
  <div class="analytics">
    <span class = "analytics-p">数据总览</span>
    <el-tabs v-model="select" class="demo-tabs" type="card">
      <el-tab-pane label="近7日" name="week">
          <span class="scan card" @click="change('浏览','week')">
            <span class="name">观看</span>
            <span class="num">{{ data.weekPersonalData.views }}</span>
          </span>
        <span class="like card" @click="change('点赞','week')">
            <span class="name">点赞</span>
            <span class="num">{{ data.weekPersonalData.likes }}</span>
             <span class="compare">{{calculateTrend(data.weekPersonalData.likes,data.weekPersonalData.likesCompare)}}</span>
          </span>
        <span class="collect card" @click="change('收藏','week')">
            <span class="name">收藏</span>
            <span class="num">{{ data.weekPersonalData.collects }}</span>
            <span class="compare">{{calculateTrend(data.weekPersonalData.collects,data.weekPersonalData.collectsCompare)}}</span>
          </span>
        <span class="comment card" @click="change('评论','week')">
            <span class="name">评论</span>
            <span class="num">{{ data.weekPersonalData.comments }}</span>
            <span class="compare">{{calculateTrend(data.weekPersonalData.comments,data.weekPersonalData.commentsCompare)}}</span>
          </span>
        <span class="fans card" @click="change('涨粉','week')">
            <span class="name">涨粉</span>
            <span class="num">{{ data.weekPersonalData.follows }}</span>
          </span>
      </el-tab-pane>
      <el-tab-pane label="近30天" name="month">
          <span class="scan card" @click="change('浏览','month')">
            <span class="name">观看</span>
            <span class="num">{{ data.monthPersonalData.views }}</span>
          </span>
        <span class="like card" @click="change('点赞','month')">
            <span class="name">点赞</span>
            <span class="num">{{ data.monthPersonalData.likes }}</span>
             <span class="compare">{{calculateTrend(data.monthPersonalData.likes,data.monthPersonalData.likesCompare)}}</span>
          </span>
        <span class="collect card" @click="change('收藏','month')">
            <span class="name">收藏</span>
            <span class="num">{{ data.monthPersonalData.collects }}</span>
            <span class="compare">{{calculateTrend(data.monthPersonalData.collects,data.monthPersonalData.collectsCompare)}}</span>
          </span>
        <span class="comment card" @click="change('评论','month')">
            <span class="name">评论</span>
            <span class="num">{{ data.monthPersonalData.comments }}</span>
            <span class="compare">{{calculateTrend(data.monthPersonalData.comments,data.monthPersonalData.commentsCompare)}}</span>
          </span>
        <span class="fans card" @click="change('涨粉','month')">
            <span class="name">涨粉</span>
            <span class="num">{{ data.monthPersonalData.follows}}</span>
          </span>
      </el-tab-pane>
    </el-tabs>
    <div ref="chart" style="width: 850px; height: 400px;margin-left: -50px"></div>
    <!-- 自定义悬浮框 -->
    <div v-if="hoverData.visible"
         :style="{
         position: 'absolute',
         left: hoverData.x + 'px',
         top: hoverData.y + 'px',
         background: 'rgba(0,0,0,0.8)',
         color: 'white',
         padding: '8px',
         borderRadius: '4px',
         pointerEvents: 'none'
       }">
      {{ hoverData.date }}<br/>
      {{ type }}数：{{ hoverData.value }}
    </div>
  </div>
  <div class="data">
    <el-card class="section" shadow="never">
      <template #header>
        <div class="section-header">
          <h3>已发布笔记数据</h3>
          <el-button type="primary" plain>导出数据</el-button>
        </div>
      </template>

      <el-table :data="posts" border stripe>
        <el-table-column prop="title" label="标题" width="260" />
        <el-table-column label="发布时间" width="110">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览数" sortable width="80" />
        <el-table-column prop="likeCount" label="点赞数" sortable width="80" />
        <el-table-column prop="collectCount" label="收藏数" sortable width="80" />
        <el-table-column prop="commentCount" label="评论数" sortable width="80" />
      </el-table>
    </el-card>
  </div>
  <div class="fans-dashboard">
    <div class="chart-container">
      <div class="header">
      <span
        :class="{ active: activeType === 'week' }"
        @click="handleChangeType('week')"
      >
        近7天
      </span>
        <span
          :class="{ active: activeType === 'month' }"
          @click="handleChangeType('month')"
        >
        近30天
      </span>
      </div>
      <div>
        <span>总粉丝数:</span>
        <span>{{rawData.fans}}</span>
        <span>新增粉丝数:</span>
        <span>{{activeType === 'month' ? rawData.monthTotalFans : rawData.weekTotalFans}}</span>
      </div>
      <div ref="chartEl" style="width: 750px; height: 400px;margin-left: -10px"></div>
    </div>
  </div>
</div>
</template>

<style scoped lang="scss">
.analytics {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;

  .card {
    display: inline-block;
    width: 125px;
    height: 85px;
    border: 1px solid #ddd9d9;
    margin-right: 20px;
    border-radius: 6px;
    position: relative;

    .name {
      position: absolute;
      left: 10px;
      top: 10px;
      color: #7a7a7a;
      font-size: 14px;
    }

    .num {
      position: absolute;
      left: 8px;
      top: 35px;
    }

    .compare {
      position: absolute;
      left: 10px;
      top: 60px;
      color: #ed0b38;
      font-size: 13px;
    }

  }


}

.data{
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  margin-top: 50px;
  .section {

    &-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.fans-dashboard {
  overflow: hidden;
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-top: 50px;

  .stats-container {
    padding: 20px;

    .stat-card {
      margin-bottom: 24px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;

      .stat-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;

        .stat-title {
          font-size: 14px;
          color: #606266;
        }
      }

      .stat-value {
        font-size: 28px;
        font-weight: 600;
        color: #303133;
      }
    }

    .data-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;

      .data-item {
        padding: 16px;
        border-radius: 8px;
        position: relative;
        transition: transform 0.2s;

        &:hover {
          transform: translateY(-2px);
        }

        &.success {
          background: #f0f9eb;
          color: #67c23a;
        }

        &.danger {
          background: #fef0f0;
          color: #f56c6c;
        }

        .data-label {
          font-size: 14px;
          margin-bottom: 8px;
        }

        .data-value {
          font-size: 20px;
          font-weight: 600;
          margin-bottom: 4px;
        }

        .trend-icon {
          position: absolute;
          right: 16px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 24px;
        }

        .growth-rate {
          font-size: 12px;
          opacity: 0.8;
        }
      }
    }
  }
}
</style>
